package com.zheng.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zheng.common.entity.WeixinUser;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2018/5/21
 * Time: 17:19
 */
public class WeixinUtil {
    private final static Logger _log = LoggerFactory.getLogger(WeixinUtil.class);

    private static final String CORP_ID = "ww571a5b833e7c2449";
    //通讯录
    private static final String SECRET = "6NTKIfbJEPTJRvtfaJXPhdHRE5FeLZR3ixIii53umJc";
    //打卡
    private static final String SIGN_SECRET = "YCWov1fi9i8wJj5c-q8pOK5pnAoxAWHoLw_H7haaMNE";
    //审核
    private static final String EXAMINE_SECRET = "UXXzsoLw-Cf-nRg_OrPSL1Ts35F6Ng43_SM-_K50ios";

    /**
     * 获取不同类型的token
     *
     * @param secret
     * @return
     */
    @Cacheable(cacheNames = "zheng-oa-admin-weixin-ehcache", key = "#secret")
    public static String getAccessToken(String secret) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CORP_ID + "&corpsecret=" + secret;
        JSONObject jsonObject = HttpGetJSON(url);
        return jsonObject.getString("access_token");
    }

    /**
     * 新增组织到企业微信
     *
     * @param id   organization 的id
     * @param name organization 的name
     * @param pid  organization 的pid
     * @return
     */
    public static boolean insertOrganization(Integer id, String name, Integer pid) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + getAccessToken(SECRET);
        JSONObject param = new JSONObject();
        param.put("id", id);
        param.put("name", name);
        param.put("parentid", pid);
        JSONObject result = HttpPostJSON(url, param.toJSONString());
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    /**
     * 修改组织到企业微信
     *
     * @param id   organization 的id
     * @param name organization 的name
     * @param pid  organization 的pid
     * @return
     */
    public static boolean updateOrganization(Integer id, String name, Integer pid) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + getAccessToken(SECRET);
        JSONObject param = new JSONObject();
        param.put("id", id);
        param.put("name", name);
        param.put("parentid", pid);
        JSONObject result = HttpPostJSON(url, param.toJSONString());
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    /**
     * 删除组织到企业微信
     *
     * @param id
     * @return
     */
    public static boolean deleteOrganization(Integer id) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=" + getAccessToken(SECRET) + "&id=" + id;
        JSONObject result = HttpPostJSON(url, "");
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    public static JSONArray getOrganizationList(Integer id) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + getAccessToken(SECRET);
        if (id != null) {
            url += "&id=" + id;
        }
        JSONObject result = HttpGetJSON(url);
        return result.getJSONArray("department");
    }

    public static boolean insertUser(WeixinUser user) {
        JSONObject param = new JSONObject();
        String accessToken = getAccessToken(SECRET);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accessToken;
        param.put("userid", user.getUserid());
        param.put("english_name", user.getEnglish_name());
        param.put("name", user.getName());
        param.put("department", user.getDepartment());
        param.put("order", user.getOrder());
        param.put("position", user.getPosition());
        param.put("gender", user.getGender());
        param.put("email", user.getEmail());
        param.put("mobile", user.getMobile());
        param.put("avatar_mediaid", user.getAvatar_mediaid());
        JSONObject result = HttpPostJSON(url, param.toJSONString());
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    public static boolean updateUser(WeixinUser user) {
        //todo 修改部门（审核）需要设置organizationId
        JSONObject param = new JSONObject();
        String accessToken = getAccessToken(SECRET);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + accessToken;
        String userId = user.getUserid();
        if (StringUtils.isBlank(userId)) {
            return false;
        }
        param.put("userid", userId);
        param.put("english_name", user.getEnglish_name());
        param.put("name", user.getName());
        param.put("department", user.getDepartment());
        param.put("order", user.getOrder());
        param.put("position", user.getPosition());
        param.put("gender", user.getGender());
        param.put("email", user.getEmail());
        param.put("mobile", user.getMobile());
        param.put("avatar_mediaid", user.getAvatar_mediaid());
        JSONObject result = HttpPostJSON(url, param.toJSONString());
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    public static boolean deleteUser(Integer id) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + getAccessToken(SECRET) + "&userid=" + id;
        JSONObject result = HttpGetJSON(url);
        return result != null && result.get("errcode") != null && result.getInteger("errcode") == 0;
    }

    public static JSONArray getUserListByOrganizationId(Integer organizationId) {
        String accessToken = getAccessToken(SECRET);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?" +
                "access_token=" + accessToken + "&department_id=" + organizationId + "&fetch_child=0";
        return HttpGetJSON(url).getJSONArray("userlist");
    }

    public static JSONArray getCheckInData(Long startTime, Long endTime, List<String> usernameList) {
        String url = "https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=" + getAccessToken(SIGN_SECRET);
        JSONObject param = new JSONObject();
        JSONArray checkInData = new JSONArray();
        param.put("opencheckindatatype", 3);
        param.put("starttime", startTime);
        param.put("endtime", endTime);
        ArrayList<String> names = new ArrayList<>();
        for (int i = 0; i < usernameList.size(); i++) {
            names.add(usernameList.get(i));
            //每当满足99个或者是最后一组的时候，获取这一组的考勤信息
            if ((i % 99 == 0 && i > 0) || i == usernameList.size() - 1) {
                param.put("useridlist", names);
                //获取数据
                JSONObject result = HttpPostJSON(url, param.toJSONString());
                checkInData.addAll(result.getJSONArray("checkindata"));
                names = new ArrayList<>();
            }
        }
        return checkInData;
    }

    public static JSONArray getApprovalArray(Long startTime, Long endTime) {
        int maxSize = 100;
        JSONArray allApprovalArray = new JSONArray();
        String url = "https://qyapi.weixin.qq.com/cgi-bin/corp/getapprovaldata?access_token=" + getAccessToken(EXAMINE_SECRET);
        JSONObject param = new JSONObject();
        param.put("starttime", startTime);
        param.put("endtime", endTime);
        //第一次获取数据
        JSONObject result = HttpPostJSON(url, param.toJSONString());
        JSONArray approvalArray = result.getJSONArray("data");
        allApprovalArray.addAll(approvalArray);
        //如果数据超过100条，多次获取
        while (approvalArray.size() >= maxSize) {
            JSONObject lastApproval = approvalArray.getJSONObject(maxSize - 1);
            param.put("next_spnum", lastApproval.getString("sp_num"));
            result = HttpPostJSON(url, param.toJSONString());
            //重新获得当前最后一个未开始的数据
            approvalArray = result.getJSONArray("data");
            allApprovalArray.addAll(approvalArray);
        }
        return allApprovalArray;
    }


    public static JSONObject HttpGetJSON(String url) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
        JSONObject jsonObject = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            String result = null;
            try {
                result = EntityUtils.toString(httpEntity);
//                result = new String(result.getBytes("ISO-8859-1"), "UTF-8");
            } catch (Exception e) {
                _log.error(e.getMessage());
            }// 返回json格式：
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }

    public static JSONObject HttpPostJSON(String url, String param) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setEntity(new StringEntity(param, Charset.forName("UTF-8")));
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
        } catch (IOException e) {
            _log.error(e.getMessage());
            return null;
        }
        JSONObject jsonObject = null;
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity httpEntity = response.getEntity();
            String result = null;
            try {
                result = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
                _log.error(e.getMessage());
            }// 返回json格式：
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }

    private static JSONObject getWeixinDept() {
        String accessToken = getAccessToken(SECRET);
        String url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=" + accessToken;
        return HttpGetJSON(url);
    }
}
